﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zhp.Common.Helper
{
    public static class JsonHelper
    {
        public static JsonSerializerSettings settings = new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() };
    

        /// <summary>
        /// JSON 字符串转 Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T ToObject<T>(this string json)
        {
            json = json.Replace("&nbsp;", "");
            return json == null ? default(T) : JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// Object 转 JSON字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj, bool toLower = false)
        {
            return obj == null ? string.Empty : JsonConvert.SerializeObject(obj, toLower == true ? settings : null);
        }

        /// <summary>
        /// JSON 字符串转 JObject
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static JObject ToJObject(this string json)
        {
            return json == null ? JObject.Parse("{}") : JObject.Parse(json.Replace("&nbsp;", ""));
        }

        /// <summary>
        /// Dictionary 字符串转 Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dictionary"></param>
        /// <returns></returns>
        public static T ToObject<T>(this IDictionary<string, object> dictionary)
        {
            return dictionary.ToJson().ToObject<T>();
        }
    }
}
